<!-- 实时流量 -->
<template>
  <div class="dashboard-editor-container">
    <el-tabs type="border-card">
      <el-tab-pane label="拓扑看板">
        <vue2-org-tree 
          :data="tableData2" 
          :renderContent="renderContent"
          :horizontal="true" 
          @on-expand="onExpand"
          @on-node-click="NodeClick"
          collapsable
          style="width:100%;">
        </vue2-org-tree>
      </el-tab-pane>
      <el-tab-pane label="列表看板">
        <el-row style="background: #fff; padding: 16px 16px 0;">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" style="padding-right: 8px;margin: 0px 0 32px;">
            <!-- <span class="title">终端信息列表</span> -->
            <div class="terminal">
              <el-tag effect="dark" @click="terminalClick(2)">全部终端：{{ allStayus }}</el-tag>
              <el-tag type="success" effect="dark" @click="terminalClick(1)">在线终端：{{ onStatus }}</el-tag>
              <el-tag type="info" effect="dark" @click="terminalClick(0)">离线终端：{{ offStatus }}</el-tag>
            </div>
            <el-table 
              border 
              stripe  
              default-expand-all
              style="width: 100%;z-index:1000; margin-top: 15px" 
              :data="tableData" 
              row-key="ID" 
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
              <el-table-column label="序号" width="80" type="index" align="left" show-overflow-tooltip></el-table-column>
              <el-table-column label="从属部门" prop="Department" align="left" width="120" show-overflow-tooltip></el-table-column>
              <el-table-column label="终端用户" prop="Name" align="left" width="120" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-show="scope.row.Name === undefined"></span>
                  <span v-show="scope.row.Name !== undefined">{{ scope.row.Name || '--'  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="联系电话" prop="Mobile" align="left" width="120" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-show="scope.row.Mobile === undefined"></span>
                  <span v-show="scope.row.Mobile !== undefined">{{ scope.row.Mobile || '--'  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="在线状态" prop="Status" align="left" show-overflow-tooltip width="80">
                <template slot-scope="scope">
                  <span v-show="scope.row.Status === undefined"></span>
                  <span v-show="scope.row.Status !== undefined" :style="{color: scope.row.Status === 1 ? '#67C23A' : '#F56C6C'}">{{ scope.row.Status === 1 ? '在线' : '离线'  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="在线时长" prop="LoginTime" align="left" width="120">
                <template slot-scope="scope">
                  <span v-show="scope.row.LoginTime === undefined"></span>
                  <span v-show="scope.row.LoginTime !== undefined">{{ (scope.row.LoginTime && scope.row.Status === 1) ? scope.row.LoginTime : '--'  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="终端地址" prop="DeviceIP" align="left" width="120" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-show="scope.row.DeviceIP === undefined"></span>
                  <span v-show="scope.row.DeviceIP !== undefined">{{ scope.row.DeviceIP || '--'  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="版本号" prop="Version" align="left" width="140" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-show="scope.row.Version === undefined"></span>
                  <span v-show="scope.row.Version !== undefined">{{ scope.row.Version || '--'  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作系统" prop="OsInfo" align="left" width="120" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-show="scope.row.OsInfo === undefined"></span>
                  <span v-show="scope.row.OsInfo !== undefined">{{ scope.row.OsInfo || '--'  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="计算机名称" width="180" align="left" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-show="scope.row.ComputerName === undefined"></span>
                  <span v-show="scope.row.ComputerName !== undefined">{{ scope.row.ComputerName || '--'  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="行为审计" width="80" align="left" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-show="scope.row.RightDC === undefined"></span>
                  <span v-show="scope.row.RightDC !== undefined" :style="{color: scope.row.behavioralAudit === '正常' ? '#67C23A' : '#F56C6C'}">{{ scope.row.behavioralAudit  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="开通权限" align="left" show-overflow-tooltip>
                <!-- <template slot-scope="scope">
                  <span v-show="scope.row.RightAMazon === 1">亚马逊助手，</span>
                  <span v-show="scope.row.RightAI === 1">AI助手，</span>
                  <span v-show="scope.row.RightV2ray === 1">网络加速，</span>
                  <span v-show="scope.row.RightDC === 1">行为审计</span>
                </template> -->
                <template slot-scope="scope">
                  <span v-show="scope.row.RightDC === 1">行为，</span>
                  <span v-show="scope.row.RightAMazon === 1">助手，</span>
                  <span v-show="scope.row.RightAI === 1">AI，</span>
                  <span v-show="scope.row.RightV2ray === 1">加速，</span>
                  <span v-show="scope.row.RightData === 1">资源</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" show-overflow-tooltip fixed="right">
                <template slot-scope="scope">
                  <el-button v-show="scope.row.Name !== undefined" type="primary" size="mini" @click="LookDetails(scope.row)">详情</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <el-dialog v-el-drag-dialog title="设备详情" :close-on-click-modal="false" :visible.sync="dialogTableVisible" width="70%">
      <div>
        <el-row>
          <el-descriptions class="margin-top" :column="3"  border>
            <el-descriptions-item>
              <template slot="label">
                从属部门
              </template>
              {{dialogForm.Department}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                终端用户
              </template>
              {{dialogForm.Name}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                联系电话
              </template>
              {{dialogForm.Mobile}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                在线状态
              </template>
              <span :style="{color: dialogForm.Status === 1 ? '#67C23A' : '#F56C6C'}">{{dialogForm.Status === 1 ? '在线' : '离线'}}</span>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                在线时长
              </template>
              {{dialogForm.LoginTime}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                终端地址
              </template>
              {{dialogForm.DeviceIP}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                版本号
              </template>
              {{dialogForm.Version}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                操作系统
              </template>
              {{dialogForm.OsInfo}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                计算机名称
              </template>
              {{dialogForm.ComputerName}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                QQ状态
              </template>
              {{dialogForm.QQ_Status}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                状态解释
              </template>
              {{dialogForm.QQ_reason}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                QQ版本
              </template>
              {{dialogForm.QQ_Version}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                微信状态
              </template>
              {{dialogForm.WX_Status}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                状态解释
              </template>
              {{dialogForm.WX_reason}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                微信版本
              </template>
              {{dialogForm.WX_Version}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                开通业务
              </template>
              {{dialogForm.RightDC === 1 ? '行为分析,' : ''}}
              {{dialogForm.RightAMazon === 1 ? '亚马逊助手,' : ''}}
              {{dialogForm.RightAI === 1 ? 'AI助手,' : ''}}
              {{dialogForm.RightV2ray === 1 ? '网络加速,' : ''}}
              {{dialogForm.RightData === 1 ? '精准资源' : ''}}
            </el-descriptions-item>
          </el-descriptions>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogTableVisible = false;">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Vue2OrgTree from "vue2-org-tree";
import 'vue2-org-tree/dist/style.css'
import { connrequest } from "@/api/firstPage.js"
import connsearch from "@/components/connSearch";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import linechart from "./components/linechart.vue";
import conntable from "./components/conntable.vue";
import { formatDuration, parseTime, bytesToSize, getuuid } from "@/utils/index.js";
export default {
  components: { connsearch, linechart, conntable, Vue2OrgTree },
  directives: { elDragDialog },
  data() {
    return {
      size: '',
      CS: {
          'min-width': '200px',   //最小宽度
          'word-break': 'break-all'  //过长时自动换行
      },
      LS: {
          'text-align': 'center',
          'height': '10%',
          'min-width': '150',
          'word-break': 'keep-all'
      },
      dialogTableVisible: false,
      departmentStats: [],
      dialogForm: {},
      onStatus: 0,
      offStatus: 0,
      allStayus: 0,
      Name:'',
      time: 30000,
      tableData: [],
      tableData1: [],
      tableData2: {},
      lineChartData: {
        time:[],
        expectedData: [],
        actualData: []
      },
      rowIndex:''
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  beforeDestroy() {
  },
  methods: {
    toggleExpand(data, val) {
      var _this = this;
      if (Array.isArray(data)) {
        data.forEach(function (item) {
          _this.$set(item, "expand", item.children?.length < 15);
          if (item.children) {
            _this.toggleExpand(item.children, item.children?.length < 15);
          }
        });
      } else {
        this.$set(data, "expand", data.children.length < 15);
        if (data.children) {
          _this.toggleExpand(data.children, data.children.length < 15);
        }
      }
    },
    collapse(list) {
      var _this = this;
      list.forEach(function(child) {
        if (child.expand) {
          child.expand = false;
        }
        child.children && _this.collapse(child.children);
      });
    },
    onExpand(e,data) {
      if ("expand" in data) {
        data.expand = !data.expand;
        if (!data.expand && data.children) {
          this.collapse(data.children);
        }
      } else {
        this.$set(data, "expand", true);
      }
    },
    NodeClick(e, data){
      if(data.Name){
        this.LookDetails(data)
      }
    },
    LookDetails(row){
      const QQarr = ['QQ未安装', 'QQ未运行', '注入QQ成功', '注入QQ失败', '策略配置不需要注入', '状态查询未完成']
      const WXarr = ['WX未安装', 'WX未运行', '注入WX成功', '注入WX失败', '策略配置不需要注入', '状态查询未完成']
      this.dialogTableVisible = true
      this.dialogForm = {
        ...row, 
        QQ_reason: QQarr[row.QQ_Status], 
        WX_reason: WXarr[row.WX_Status], 
        QQ_Status: (row.QQ_Status === 3) ? '异常' : '正常', //row.QQ_Status === 1 || 
        WX_Status: (row.WX_Status === 3) ? '异常' : '正常'  //row.WX_Status === 1 || 
      }
    },
    rowStyle ({ row, rowIndex }) {
      if (this.rowIndex === rowIndex) {
        return {
          'background-color': '#ffeecf !important'
        }
      }
    },
    rowClassName ({ row, rowIndex }) {
      row.index = rowIndex
    },
    async getData(status = 2){
      const res = await connrequest('GetEmployeeStatus')
      let on = 0
      res.Data = res.Data || []
      res.Data = res.Data.map(item => {
        if(item.Status === 1){
          on++
        }
        item.LoginTime = item.LoginTime ? formatDuration(Date.now() / 1000 - item.LoginTime) : '-'
        item.behavioralAudit = ( item.QQ_Status === 3 ||  item.WX_Status === 3) ? '异常' : '正常'  //item.QQ_Status === 1 ||   item.WX_Status === 1 ||
        return item
      })
      this.onStatus = on
      this.offStatus = res.Data.length - on
      this.allStayus = this.onStatus + this.offStatus
      if(status === 1){
        res.Data = res.Data.filter( item => item.Status === status )
      }
      if(status === 0){
        res.Data = res.Data.filter( item => item.Status !== 1 )
      }
      // 把终端根据在线状态和在线时长进行排序
      let arr = [...res.Data]
      // 定义排序比较函数
      function compare(a, b) {
        // 首先根据Status从大到小排序
        if (a.Status === 1 && b.Status !== 1) {
          return -1;
        } else if (a.Status !== 1 && b.Status === 1) {
          return 1;
        } else {
          // 如果Status相同，根据LoginTime从大到小排序
          if (a.LoginTime > b.LoginTime) {
            return -1;
          } else if (a.LoginTime < b.LoginTime) {
            return 1;
          } else {
            return 0;
          }
        }
      }
      arr.sort(compare);
      let sortarr = this.transformData(arr)
      const res2 = await connrequest('GetDCDInfo')
      this.tableData = this.transformData(arr)
      this.tableData2 = {Department: res2.Data.AgentName, children: sortarr, AgentName: res2.Data.AgentName}
      this.toggleExpand(this.tableData2, true)
      // 统计每个部门的在线和离线个数
      const departmentStats = res.Data.reduce((result, item) => {
        const department = item.Department;
        const status = item.Status;
        // 如果部门还未统计过，则初始化统计数据
        if (!result[department]) {
          result[department] = {
            Department: item.Department,
            onStatus: 0,
            offStatus: 0,
          };
        }
        // 根据状态增加在线或离线个数
        if (status === 1) {
          result[department].onStatus++;
        } else{
          result[department].offStatus++;
        }
        return result;
      }, {});
      this.departmentStats = departmentStats
    },
    renderContent(h, data) {
      if(!data.Name){
        for (const key in this.departmentStats) {
          if (this.departmentStats[key].Department === data.Department) {
            data.onStatus = this.departmentStats[key].onStatus
            data.offStatus = this.departmentStats[key].offStatus
          }
        }
        return (
          <div style="width: 300px;height:100px;display:flex;padding:0;border:1px solid #2491fc;">
            <div style="width:28px;background:#2491fc;color:#fff;padding:5px;text-align:center;line-height:30px;"><p>{data.AgentName ? '公司' : '部门'}</p></div>
            <div>
              <div style="font-size:14px;line-height:20px;color:#2491fc;font-weight:600;padding-left:20px;padding-top:10px;text-align:left;">{data.Department}</div>
              <div style="font-size:14px;line-height:20px;color:#23ce69;padding-left:20px;padding-top:10px;text-align:left;">在线：{data.AgentName ? this.onStatus : data.onStatus}人</div>
              <div style="font-size:14px;line-height:20px;color:#f36b6e;padding-left:20px;padding-top:10px;text-align:left;">离线：{data.AgentName ? this.offStatus : data.offStatus}人</div>
            </div>
          </div>
        );
      }
      else if(data.Status === 1){
        return (
          <div style="width: 300px;height:100px;display:flex;padding:0;border:1px solid #23ce69;cursor: pointer;">
            <div style="width:28px;background:#23ce69;color:#fff;padding:5px;text-align:center;line-height:30px;"><p>在线</p></div>
            <div>
              <div style="font-size:14px;line-height:20px;color:#23ce69;font-weight:600;padding-left:20px;padding-top:10px;text-align:left;">{data.Name}   ({data.Mobile})</div>
              <div style="font-size:14px;line-height:20px;color:#bbb;padding-left:20px;text-align:left;">{data.DeviceIP}</div>
              <div style="font-size:14px;line-height:20px;color:#bbb;padding-left:20px;text-align:left;">{data.LoginTime}</div>
              <div style="font-size:14px;line-height:20px;color:#bbb;padding-left:20px;text-align:left;">{data.RightAMazon === 1 ? '助手，' : ''} {data.RightAI === 1 ? 'AI，' : ''} {data.RightV2ray === 1 ? '加速，' : ''} {data.RightDC === 1 ? '行为，' : ''} {data.RightData === 1 ? '资源' : ''} </div>
            </div>
          </div>
        );
      }else{
        return (
          <div style="width: 300px;height:100px;display:flex;padding:0;border:1px solid #f36b6e;cursor: pointer;">
            <div style="width:28px;background:#f36b6e;color:#fff;padding:5px;text-align:center;line-height:30px;"><p>离线</p></div>
            <div>
              <div style="font-size:14px;line-height:20px;color:#f36b6e;font-weight:600;padding-left:20px;padding-top:10px;text-align:left;">{data.Name}   ({data.Mobile})</div>
              <div style="font-size:14px;line-height:20px;color:#bbb;padding-left:20px;text-align:left;">{data.DeviceIP}</div>
              <div style="font-size:14px;line-height:20px;color:#bbb;padding-left:20px;text-align:left;">{data.LoginTime}</div>
              <div style="font-size:14px;line-height:20px;color:#bbb;padding-left:20px;text-align:left;">{data.RightAMazon === 1 ? '助手，' : ''} {data.RightAI === 1 ? 'AI，' : ''} {data.RightV2ray === 1 ? '加速，' : ''} {data.RightDC === 1 ? '行为，' : ''} {data.RightData === 1 ? '资源' : ''} </div>
            </div>
          </div>
        );
      }
      
    },
    terminalClick(status){
      this.getData(status)
    },
    transformData(data) {
      const departments = {};
      for (const item of data) {
        const departmentName = item.Department;
        if (!departments[departmentName]) {
          departments[departmentName] = { Department: departmentName, children: [] };
        }
        departments[departmentName].children.push(item);
      }
      Object.values(departments).forEach(item => {
        item.ID = item.ID || getuuid();
      });
      return Object.values(departments);
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";
.terminal{
  margin: 10px 0px;
  .el-tag{
    cursor: pointer;
    margin-right: 10px;
  }
}


</style>
<style>
.org-tree-node-label .org-tree-node-label-inner{
  padding: 0px;
}
</style>